<!--工作岗位管理-->
<template>
  <div id="post" class="app-container">
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar @refresh="handleFilter" @create="handleCreate" @remove="removeRecord">
          <template slot="rightTool">
            <search v-model="listQuery.keyword" placeholder="请输入关键字" @search="handleFilter" />
          </template>
        </table-toolbar>
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="岗位名称" prop="name" sortable width="260">
          <template slot-scope="scope">
            <span class="color-primary">({{ scope.row.code }})</span>
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="岗位类型" prop="type" sortable width="120">
          <template slot-scope="scope">
            {{ scope.row.type | dictFormat }}
          </template>
        </el-table-column>
        <el-table-column label="岗位排序" prop="orders" sortable align="center" width="120" />
        <el-table-column label="是否启用" prop="isDisabled" width="80" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              @change="changeIsState(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="岗位描述" prop="description" min-width="200" show-overflow-tooltip />
        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="postRules"
          :model="postRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="岗位编号:" prop="code">
            <el-input v-model="postRecord.code" :disabled="sideBox.status==='update'" placeholder="请输入岗位编号" />
          </el-form-item>
          <el-form-item label="岗位名称:" prop="name">
            <el-input v-model="postRecord.name" maxlength="20" show-word-limit placeholder="请输入岗位名称" />
          </el-form-item>
          <el-form-item label="岗位类型:" prop="type">
            <data-dict-select v-model="postRecord.type" :code="'postType'" placeholder="请选择岗位类型" />
          </el-form-item>
          <el-form-item label="字典排序:" prop="orders">
            <el-input-number v-model="postRecord.orders" placeholder="请输入排序" show-word-limit :max="9999" style="width:100%" />
          </el-form-item>
          <el-form-item label="岗位描述:" prop="description">
            <el-input
              v-model="postRecord.description"
              :rows="4"
              type="textarea"
              maxlength="200"
              show-word-limit
              placeholder="请输入岗位描述" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
export default {
  components: {},

  data() {
    return {
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: '',
        sort: '-orders'
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create' // 对话框状态
      },
      postRecord: {
      },
      postRules: {
        name: [
          { required: true, message: '请输入岗位名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入岗位编号', trigger: 'blur' }
        ],
        orders: [
          { required: true, message: '请输入岗位排序', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择岗位类型', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 表格自带方法开始
    /**
     * 全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /**
     * 表格行数据单击
     */
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /**
     * 表格列排序
     */
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = '-orders'
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    async fetchData() {
      const response = await this.$store.dispatch('postPage', this.listQuery)
      this.list = response.records
      this.list.filter((item) => {
        item.status = !item.status
        return true
      })
      this.total = response.total
    },

    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: '-orders'
      }

      this.fetchData()
    },

    /* 新增*/
    handleCreate() {
      this.postRecord = {
        orders: 1
      }
      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增工作岗位'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('postSave', this.postRecord).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 编辑*/
    handleUpdate(row) {
      this.postRecord = Object.assign({}, row) // copy obj
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑[' + this.postRecord.name + ']'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData() {
      this.postRecord.status = null
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.postRecord)
          this.$store.dispatch('postUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('postRemove', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    },

    changeIsState(row) {
      var temp = Object.assign({}, row) // copy obj

      this.$confirm('您确定' + (temp.status === false ? '禁用' : '启用') + '岗位[' + temp.name + '], 是否继续?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          const params = {
            id: temp.id,
            status: !temp.status
          }
          this.$store.dispatch('changePostState', params).then(response => {
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            row.status = !row.status
          })
        }).catch(() => {
          row.status = !row.status
        })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
